package com.yingyi.exceptionhandler;

import com.yingyi.enums.ExceptionEnums;
import com.yingyi.exception.CustomizedException;
import com.yingyi.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)
    public JsonResult exception(Exception e) {
        e.printStackTrace();
        log.info("发生 Exception 异常");
        return JsonResult.error(ExceptionEnums.ERROR);
    }

    @ExceptionHandler(CustomizedException.class)
    public JsonResult exception(CustomizedException e) {
        e.printStackTrace();
        log.info("发生 CustomizedException 异常, message：" + e.getMessage());
        return JsonResult.error(e);
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult exception(MethodArgumentNotValidException e) {
        e.printStackTrace();
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(item -> sb.append(item.getDefaultMessage()).append(" ,"));
        String errString = sb.toString();
        errString = errString.substring(0, errString.length() - 2);
        log.info("发生 CustomizedException 异常, message：" + errString);
        return JsonResult.error(errString);
    }
}
